//
// Created by james on 2021/11/2.
//

#include "JavaCallHelper.h"

JavaCallHelper::JavaCallHelper(JavaVM *pVm, JNIEnv *pEnv, jobject &jobj) : pVm(pVm),pEnv(pEnv) {
    this->jobj = pEnv->NewGlobalRef(jobj);
    jclass jclass1 = pEnv->GetObjectClass(this->jobj);

    onParpare = pEnv->GetMethodID(jclass1,"onParpare","()V");
    onError = pEnv->GetMethodID(jclass1,"onError","(I)V");
    onProgress = pEnv->GetMethodID(jclass1,"onProgress","(I)V");
}
void JavaCallHelper::onPerpare(int thread) {
    if (thread == THREAD_CHILD){
        JNIEnv* jniEnv;
        if (pVm->AttachCurrentThread(&jniEnv,NULL) != JNI_OK){
            return;
        }
        jniEnv->CallVoidMethod(jobj,onParpare);
        pVm->DetachCurrentThread();
    } else if (thread == THREAD_MAIN){
        pEnv->CallVoidMethod(jobj, onParpare);
    }
}
void JavaCallHelper::_onError(int errorCode, int thread) {
    if (thread == THREAD_CHILD){
        JNIEnv* jniEnv;
        if (pVm->AttachCurrentThread(&jniEnv,NULL) != JNI_OK){
            return;
        }
        jniEnv->CallVoidMethod(jobj,onError,errorCode);
        pVm->DetachCurrentThread();
    } else if (thread == THREAD_MAIN){
        pEnv->CallVoidMethod(jobj, onError,errorCode);
    }
}
